 /*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.vng.zing.survey.controller;

import com.vng.zing.survey.memcached.SurveyCache;
import com.vng.zing.survey.thrift.client.SurveyClient;
import com.vng.zing.survey.thrift.model.AnswerItem;
import com.vng.zing.survey.thrift.model.QuesType;
import com.vng.zing.survey.thrift.model.Question;
import com.vng.zing.survey.thrift.model.QuestionStats;
import com.vng.zing.survey.thrift.model.SurveyItemResult;
import com.vng.zing.survey.thrift.model.SurveyStatsItem;
import com.vng.zing.survey.thrift.model.SurveyStatsResult;
import com.vng.zing.survey.thrift.model.Error;
import com.vng.zing.survey.thrift.model.SurveyStatsPerDayItem;
import hapax.Template;
import hapax.TemplateDataDictionary;
import hapax.TemplateDictionary;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.vng.zing.survey.model.CommonModel;
import com.vng.zing.survey.model.RenderModel;
import com.vng.zing.survey.thrift.model.AnswerList;
import com.vng.zing.survey.thrift.model.SurveyItem;
import com.vng.zing.survey.thrift.model.SurveyStatsAllItem;
import com.vng.zing.survey.thrift.model.UserType;
import com.vng.zing.survey.utility.TimeDay;

/**
 *
 * @author namhh
 */
public class StatisticController extends BaseController {

    private static UserType userType = UserType.USER;

    @Override
    public String render(HttpServletRequest req, HttpServletResponse resp) throws IOException, Exception {
        TemplateDataDictionary dic = TemplateDictionary.create();
        boolean isChart = false;
        if (req.getParameter("id") == null) {
            return showError("Không tìm thấy khảo sát yêu cầu!");
        }
        int idSurvey = Integer.parseInt(req.getParameter("id"));
        String[] value = new String[1];
        value[0] = String.format("%s", idSurvey);
//        String cached = (String) getCache(new String[]{String.format("%s", idSurvey)});
//        if (cached != null && !"".equals(cached)) {
//            return cached;
//        }
        String content = "";
        TemplateDataDictionary chart = TemplateDictionary.create();
        dic.setVariable("HEADER", CommonModel.getHeader(TemplateDictionary.create(), "Kết quả thống kê"));
        dic.setVariable("FOOTER", CommonModel.getFooter(TemplateDictionary.create()));

        Map mapUser = checkMember(req, userType);
        if (mapUser.containsValue(ErrorType.FAIL) || mapUser.containsValue(ErrorType.ERROR_SYSTEM)) {
            return CommonModel.toJSON("ERROR", (String) mapUser.get("msg"));
        }
        int idUser = (int) mapUser.get("msg");
        boolean isAdmin = (boolean) mapUser.get("admin");

        SurveyClient surveyClient = SurveyClient.getInstance();
        SurveyStatsAllItem surveyStatsAllItem = surveyClient.getStatsAll(idSurvey, CommonModel.OFFSET);

        //SurveyItemResult itemResult = SurveyCache.getSurveyWithCache(idSurvey);
        if (surveyStatsAllItem.getErro() != Error.SUCCESS || surveyStatsAllItem.getSurvey().getIDUser() != idUser) {
            content = CommonModel.getError(dic, "Khảo sát không tồn tại!");
            return content;
        }
        if (surveyStatsAllItem.getSurvey().isOption() == false && !isAdmin) {
            return CommonModel.getError(dic, "Bạn không được phép xem trang này! ");
        }
        if (!isAdmin) {
            dic.setVariable("ADMIN", "hide");
        }
        SurveyItem surveyItem = surveyStatsAllItem.getSurvey();
   //     SurveyStatsResult statsResult = surveyClient.getSurveyStats(idSurvey);
        //  SurveyStatsItem statsItem surveyStatsAllItem.getSurveyStat();
        SurveyStatsItem statsItem = surveyStatsAllItem.getSurveyStat();
        List<SurveyStatsPerDayItem> dayItems = surveyClient.getListStatsSurveyPerDay(idSurvey);
        List<String> day = new ArrayList<String>();
        List<Integer> view = new ArrayList<Integer>();
        List<Integer> response = new ArrayList<Integer>();
        for (SurveyStatsPerDayItem dayItem : dayItems) {
            day.add(TimeDay.convertDateToString(new Date((long) dayItem.getDay() * 1000L)));
            view.add(dayItem.getView());
            response.add(dayItem.getResponse());
        }
        chart.setVariable("DATE", CommonModel.toJSON(day));
        chart.setVariable("VIEW", CommonModel.toJSON(view));
        chart.setVariable("RESPONSE", CommonModel.toJSON(response));

        dic.setVariable("TITLESURVEY", surveyItem.getTitle());
        dic.setVariable("DECRIPTION", surveyItem.getDescription());
        dic.setVariable("VIEW", String.valueOf(statsItem.getView()));
        dic.setVariable("RESPONSE", String.valueOf(statsItem.getResponse()));
        dic.setVariable("TIMESTART", CommonModel.getDate(surveyItem.getBeginDay()));
        dic.setVariable("TIMEEND", CommonModel.getDate(surveyItem.getEndDay()));
        dic.setVariable("RESPONSE_DETAIL_LINK", "detail?id=" + idSurvey);
        dic.setVariable("EDIT_LINK", "edit?id=" + idSurvey);
        Integer index = 1;
        DateFormat df = new SimpleDateFormat("HH:mm:ss dd/MM/yyyy");
        Date date;
        isChart = true;
        dic.setVariable("ID_SURVEY", String.format("%s", idSurvey));
        Map<Short, AnswerList> map1 = surveyStatsAllItem.getMapAnswerlist();
        for (Question question : surveyItem.getQuestions()) {
            TemplateDataDictionary sliceQuestions = dic.addSection("SLICE_QUESTION");
            sliceQuestions.setVariable("INDEX", index.toString());
            //   sliceQuestions.setVariable("TYPE_ANSWER", String.format("%s",question.getType().getValue() ));

            if (question.getType() == QuesType.MULTI_CHOICE || question.getType() == QuesType.SINGLE_SELECTION) {

                Map<Short, QuestionStats> map = statsItem.getStats();
                QuestionStats questionStats = map.get(question.getIdQues());
                if (questionStats == null) {
                    questionStats = new QuestionStats();
                    questionStats.setType(question.getType());
                    questionStats.setNumber(new ArrayList<Integer>());
                    for (String a : question.getChoices()) {
                        questionStats.getNumber().add(0);
                    }

                }
                // chart function       

                TemplateDataDictionary sliceChart = chart.addSection("SLICE_CHART");
                List<String> choice = question.getChoices();
                List<Integer> number = questionStats.getNumber();
                sliceChart.setVariable("INDEX", String.valueOf(question.getIdQues()));
                sliceChart.setVariable("TITLE", question.getTitleQues());
                sliceChart.setVariable("CHOICE", CommonModel.toJSON(choice));
                sliceChart.setVariable("NUMBER", CommonModel.toJSON(number));
                if (question.getType() == QuesType.MULTI_CHOICE) {
                    sliceChart.setVariable("TYPE", "ColumnChart");
                    sliceChart.setVariable("TYPECHART", "1");
                } else {
                    sliceChart.setVariable("TYPE", "PieChart");
                    sliceChart.setVariable("TYPECHART", "0");
                }

                TemplateDataDictionary chartAnswers = TemplateDictionary.create();
                chartAnswers.setVariable("TYPE_ANSWER", String.format("%s", question.getType().getValue()));
                chartAnswers.setVariable("INDEX", String.valueOf(question.getIdQues()));
                content = CommonModel.getStatChart(chartAnswers);
                sliceQuestions.setVariable("CHART", content);

            }
            if (question.getType() == QuesType.SINGLE_LINE || question.getType() == QuesType.MULTI_LINE) {
                sliceQuestions.setVariable("ID_QUESTION", String.format("%s", question.getIdQues()));
                sliceQuestions.setVariable("TITLE", question.getTitleQues());
                TemplateDataDictionary dicAnswers = TemplateDictionary.create();
                int page = (int) Math.floor(map1.get(question.getIdQues()).getCount() / CommonModel.OFFSET);
                List<AnswerItem> answerItems = map1.get(question.getIdQues()).getAnswerlist();
                System.out.println("answerItems:" + answerItems);
                if (answerItems.isEmpty()) {
                    dicAnswers.setVariable("CONTENT", "Chưa có câu trả lời nào!");
                    content = CommonModel.getEmpty(dicAnswers);
                } else {
                    for (int i = 0; i < answerItems.size(); i++) {
                        TemplateDataDictionary sliceAnswer = dicAnswers.addSection("SLICE_ANSWER");
                        sliceAnswer.setVariable("NUMBER", String.format("%s", i + 1));
                        sliceAnswer.setVariable("USERNAME", answerItems.get(i).getDisplayName());
                        sliceAnswer.setVariable("CONTENT", answerItems.get(i).getAnswer());

                        date = new Date(((long) answerItems.get(i).getTimeResponse()) * 1000L);
                        sliceAnswer.setVariable("TIMERESPONSE", df.format(date));

                    }

                    if (question.getType() == QuesType.SINGLE_LINE) {
                        content = CommonModel.getStatTable(dicAnswers);
                    } else {
                        content = CommonModel.getStatMutilLine(dicAnswers);
                    }

                    if (page > 0) {
                        TemplateDataDictionary dicPage = TemplateDictionary.create();
                        dicPage.setVariable("COUNT", String.format("%s", page + 1));
                        dicPage.setVariable("OFFSET", String.format("%s", CommonModel.OFFSET));
                        dicPage.setVariable("NAME", "paging_stat");
                        String paging = CommonModel.getPaging(dicPage);
                        sliceQuestions.setVariable("PAGE", paging);
                    }
                }

                sliceQuestions.setVariable("TABLE", content);

            }
            index++;
        }
        if (isChart) {
            content = CommonModel.getChartFunciton(chart);
            dic.setVariable("CHARTFUCTION", content);
        }

        Template template = RenderModel.getCTemplate("statistic");
        content = template.renderToString(dic);

        return content;
    }
}
